package com.scuec.groupfive.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import java.util.Map;
import java.util.HashMap;


@CrossOrigin
@RestController
@RequestMapping("/api/post-management")
public class PostManagementController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @GetMapping("/{postId}/likes")
    public ResponseEntity<Integer> getPostLikes(@PathVariable Long postId) {
        String sql = "SELECT COUNT(*) FROM post_likes WHERE post_id = ?";
        int likeCount = jdbcTemplate.queryForObject(sql, Integer.class, postId);
        return ResponseEntity.ok(likeCount);
    }

    @GetMapping
    public Map<String, Object> getPostList(
            @RequestParam(required = false) String content,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {

        // 构建基础查询
        StringBuilder baseSql = new StringBuilder(
                "SELECT p.*, " +
                        "COALESCE((SELECT COUNT(*) FROM post_likes WHERE post_id = p.post_id), 0) as like_count, " +
                        "COALESCE((SELECT COUNT(*) FROM post_comments WHERE post_id = p.post_id AND status = 1), 0) as comment_count, " +
                        "u.username " +
                        "FROM posts p " +
                        "LEFT JOIN users u ON p.user_id = u.user_id "
        );

        // 添加搜索条件
        if (content != null && !content.trim().isEmpty()) {
            baseSql.append("WHERE (p.content LIKE ? OR p.title LIKE ?) ");
        }

        // 获取总记录数
        String countSql = "SELECT COUNT(*) FROM (" + baseSql.toString() + ") as total";
        int total;
        if (content != null && !content.trim().isEmpty()) {
            String searchPattern = "%" + content.trim() + "%";
            total = jdbcTemplate.queryForObject(countSql, Integer.class, searchPattern, searchPattern);
        } else {
            total = jdbcTemplate.queryForObject(countSql, Integer.class);
        }

        // 添加排序和分页
        baseSql.append("ORDER BY p.created_at DESC LIMIT ? OFFSET ?");

        // 执行分页查询
        List<Map<String, Object>> result;
        if (content != null && !content.trim().isEmpty()) {
            String searchPattern = "%" + content.trim() + "%";
            result = jdbcTemplate.queryForList(baseSql.toString(), searchPattern, searchPattern, size, page * size);
        } else {
            result = jdbcTemplate.queryForList(baseSql.toString(), size, page * size);
        }

        // 构建返回结果
        Map<String, Object> response = new HashMap<>();
        response.put("content", result);
        response.put("totalElements", total);
        response.put("totalPages", (total + size - 1) / size);
        response.put("currentPage", page);
        response.put("pageSize", size);

        return response;
    }

    @DeleteMapping("/{postId}")
    public ResponseEntity<Void> deletePost(@PathVariable Long postId) {
        String sql = "UPDATE posts SET status = 0 WHERE post_id = ?";
        jdbcTemplate.update(sql, postId);
        return ResponseEntity.ok().build();
    }

    @PutMapping("/restore/{postId}")
    public ResponseEntity<Void> restorePost(@PathVariable Long postId) {
        String sql = "UPDATE posts SET status = 1 WHERE post_id = ?";
        jdbcTemplate.update(sql, postId);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/{postId}")
    public ResponseEntity<Map<String, Object>> getPostDetail(@PathVariable Long postId) {
        String sql = "SELECT p.*, " +
                "COALESCE((SELECT COUNT(*) FROM post_likes WHERE post_id = p.post_id), 0) as like_count, " +
                "COALESCE((SELECT COUNT(*) FROM post_comments WHERE post_id = p.post_id AND status = 1), 0) as comment_count, " +
                "u.username " +
                "FROM posts p " +
                "LEFT JOIN users u ON p.user_id = u.user_id " +
                "WHERE p.post_id = ?";
        Map<String, Object> post = jdbcTemplate.queryForMap(sql, postId);
        return ResponseEntity.ok(post);
    }

    @GetMapping("/{postId}/comments")
    public ResponseEntity<List<Map<String, Object>>> getPostComments(@PathVariable Long postId) {
        String sql = "SELECT " +
                "c.comment_id as commentId, " +
                "c.post_id as postId, " +
                "c.user_id as userId, " +
                "c.content, " +
                "c.parent_id as parentId, " +
                "c.status, " +
                "c.created_at as createTime, " +
                "c.updated_at as updateTime, " +
                "u.username " +
                "FROM post_comments c " +
                "LEFT JOIN users u ON c.user_id = u.user_id " +
                "WHERE c.post_id = ? AND c.status = 1 " +
                "ORDER BY c.created_at DESC";
        List<Map<String, Object>> comments = jdbcTemplate.queryForList(sql, postId);
        return ResponseEntity.ok(comments);
    }

    @PostMapping("/{postId}/comments")
    public ResponseEntity<Map<String, Object>> addComment(
            @PathVariable Long postId,
            @RequestBody Map<String, String> commentData) {
        String content = commentData.get("content");
        Long userId = Long.parseLong(commentData.get("userId"));

        String sql = "INSERT INTO post_comments (post_id, user_id, content, created_at, status) " +
                "VALUES (?, ?, ?, NOW(), 1)";

        jdbcTemplate.update(sql, postId, userId, content);

        // 获取新插入的评论
        String selectSql = "SELECT " +
                "c.comment_id as commentId, " +
                "c.post_id as postId, " +
                "c.user_id as userId, " +
                "c.content, " +
                "c.parent_id as parentId, " +
                "c.status, " +
                "c.created_at as createTime, " +
                "c.updated_at as updateTime, " +
                "u.username " +
                "FROM post_comments c " +
                "LEFT JOIN users u ON c.user_id = u.user_id " +
                "WHERE c.post_id = ? AND c.user_id = ? " +
                "ORDER BY c.created_at DESC LIMIT 1";

        Map<String, Object> newComment = jdbcTemplate.queryForMap(selectSql, postId, userId);
        return ResponseEntity.ok(newComment);
    }

    @DeleteMapping("/comments/{commentId}")
    public ResponseEntity<Void> deleteComment(@PathVariable Long commentId) {
        String sql = "UPDATE post_comments SET status = 0 WHERE comment_id = ?";
        jdbcTemplate.update(sql, commentId);
        return ResponseEntity.ok().build();
    }

    @PutMapping("/comments/{commentId}")
    public ResponseEntity<Map<String, Object>> updateComment(
            @PathVariable Long commentId,
            @RequestBody Map<String, String> commentData) {
        String content = commentData.get("content");

        String sql = "UPDATE post_comments SET content = ? WHERE comment_id = ?";
        jdbcTemplate.update(sql, content, commentId);

        // 获取更新后的评论
        String selectSql = "SELECT " +
                "c.comment_id as commentId, " +
                "c.post_id as postId, " +
                "c.user_id as userId, " +
                "c.content, " +
                "c.parent_id as parentId, " +
                "c.status, " +
                "c.created_at as createTime, " +
                "c.updated_at as updateTime, " +
                "u.username " +
                "FROM post_comments c " +
                "LEFT JOIN users u ON c.user_id = u.user_id " +
                "WHERE c.comment_id = ?";

        Map<String, Object> updatedComment = jdbcTemplate.queryForMap(selectSql, commentId);
        return ResponseEntity.ok(updatedComment);
    }
}